<template>
  <div class="code-editor">
    <div class="form-label">
      <div class="flex-center">
        <div>{{ props.label }}</div>
        <eTooltip v-if="props.tip" max-width="300" placement="top" transfer>
          <SvgIcon iconName="icon-question-circle-fill" className="question-icon"></SvgIcon>
          <template #content>
            <div style="font-size: 12px;" v-html="props.tip"></div>
          </template>
        </eTooltip>
      </div>
      <SvgIcon iconName="icon-window-maximize" className="window-icon" title="打开独立窗口编辑" @click="openModal"></SvgIcon>
    </div>
    <div class="code-view" :style="{ height: `${props.codeHeight}px`}" @dblclick="openModal">
      <pre v-if="props.modelValue">{{ props.modelValue }}</pre>
    </div>
    
    <eModal
      v-model="showModal"
      :width="800"
      :mask-closable="false"
      title="编辑代码"
      @on-ok="save"
    >
      <div style="width: 100%;height: 360px;">
        <MonacoEditor
          v-if="modalLoaded"
          ref="monacoEditorRef"
          v-model="codeValue"
          :language="props.language"
        />
      </div>
    </eModal>
  </div>
</template>

<script setup lang="ts">
  import { ref, nextTick, watch } from 'vue'
  
  interface EditorProps {
    modelValue?: string
    language?: string
    readOnly?: boolean,
    label?: string,
    codeHeight?: number,
    tip?: string
  }
  const props = withDefaults(defineProps<EditorProps>(), {
    modelValue: '',
    language: 'javascript',
    readOnly: false,
    codeHeight: 120
  })

  const emit = defineEmits<{
    (e: 'update:modelValue', newCode: string): void
  }>()

  const codeValue = ref('')

  watch(
    () => props.modelValue,
    (newVal) => {
      codeValue.value = newVal
    },
    { immediate: true }
  )

  const showModal = ref(false)
  const modalLoaded = ref(false)

  function openModal() {
    showModal.value = true
    codeValue.value = props.modelValue
    nextTick(() => {
      modalLoaded.value = true
    })
  }

  function save() {
    emit('update:modelValue', codeValue.value)
  }
</script>

<style lang="less" scoped>
  .code-editor {
    width: 100%;
    margin: 16px 0;
    font-size: 12px;
    .form-label {
      background-color: #f0f0f0;
      padding: 0 4px;
      border-radius: 4px 4px 0 0;
      color: #040B29;
      display: flex;
      justify-content: space-between;
      align-items: center;
      height: 30px;
      .question-icon {
        color: #ed4014;
        width: 1.2em;
        height: 1.2em;
        margin: 6px 0 0 4px;
      }
      .window-icon {
        width: 1.2em;
        height: 1.2em;
        cursor: pointer;
      }
    }
    .code-view {
      width: 100%;
      height: 120px;
      color: white;
      background-color: black;
      padding: 2px 4px;
      overflow: auto;
      pre {
        line-height: 14px;
      }
    }
    .flex-center {
      display: flex;
      align-items: center;
    }
  }
</style>